<?php

namespace App\Http\Middleware;

use App\Kuafu\User\Service\AuthService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use KuafuComposer\ApiTime\Service\ApiTimeService;

/**
 * 基础接口访问日志
 */
class ApiAccessLog
{
    // 需要返回值的白名单
    const RESPONSE_DATA_PATHS = [];

    public function handle(Request $request, Closure $next)
    {
        try {
            $resp = $next($request);
        } finally {
            $method         = $request->method();
            $uri            = $request->path();
            $ip             = $request->ip();
            $ua             = $request->header('User-Agent');
            $shopId         = $request->header('shopId');
            $brandId        = $request->header('brandId');
            $mapLongitude   = $request->header('mapLongitude');
            $mapLatitude    = $request->header('mapLatitude');
            $appVersionName = $request->header('AppVersionName');
            $deviceType     = $request->header('DeviceType');
            $androidID      = $request->header('AndroidID');
            $uniqueDeviceId = $request->header('UniqueDeviceId');
            $androidModel   = $request->header('AndroidModel');
            $params         = json_encode($request->all() ?? []);
            $statusCode     = $resp->getStatusCode();
            $msInt          = (int)floor((microtime(true) - LARAVEL_START) * 1000);
            $ms             = $msInt . 'ms';
            $userId         = AuthService::getUserId(false);

            if (in_array($request->path(), self::RESPONSE_DATA_PATHS)) {
                $response = (string)$resp->getContent();
            } else {
                $response = '';
            }

            $logContent = [
                'ip'           => $ip,
                'method'       => $method,
                'uri'          => $uri,
                'params'       => $params,
                'ua'           => $ua,
                'shopId'       => $shopId,
                'brandId'      => $brandId,
                'userId'       => $userId,
                'code'         => $statusCode,
                'response'     => $response,
                'lng'          => $mapLongitude,
                'lat'          => $mapLatitude,
                'appV'         => $appVersionName,
                'adId'         => $androidID,
                'uuDiD'        => $uniqueDeviceId,
                'adModel'      => $androidModel,
                'ms'           => $ms,
                'platform'     => $request->header('platform', null),
                'dBrand'       => $request->header('deviceBrand', null),
                'dModel'       => $request->header('deviceModel', null),
                'dVersion'     => $request->header('deviceVersion', null),
                'dType'        => $deviceType,
                'channel'      => $request->header('channel', null),
                'v'            => $request->header('version', null),
                'auth'         => $request->header('Authorization', null),
                'applet-token' => $request->header('applet-token', null),
                'x-local'      => $request->header('X-LOCAL-DATE', null),
            ];

            $log = '';
            foreach ($logContent as $k => $c) {

                if ($c === '' || $c === null) {
                    continue;
                }

                $log .= vsprintf("[%s:%s] ", [$k, $c]);
            }

            Log::channel('apiAccess')->info($log);

            // 慢接口统计
            try {
                $uri = $method . ':' . ($request->route()->uri ?? '');
                (new ApiTimeService('access'))->add($uri, LARAVEL_START);
            } catch (\Exception $e) {
                Log::warning($e);
            }
        }

        return $resp;
    }

//    const WHITE_PATH_SET = 'rms-apiAccessLogPath';
//
//    /**
//     * 添加需要返回值的白名单
//     */
//    public static function addPath(string $path)
//    {
//        $path = trim($path, ' ');
//        $res = Redis::sadd(self::WHITE_PATH_SET, $path);
//
//        // 每新增元素，一律整体新增1小时的超时时间
//        Redis::expire(self::WHITE_PATH_SET, 3600);
//
//        return $res;
//    }
//
//    /**
//     * 删除需要返回值的白名单
//     * @param string $path
//     */
//    public static function delPath(string $path)
//    {
//        $path = trim($path, ' ');
//        return Redis::srem(self::WHITE_PATH_SET, $path);
//    }
//
//    /**
//     * 检验是否存在
//     * @param string $path
//     * @return mixed
//     */
//    public static function checkPath(string $path)
//    {
//        // 生产环境不处理
//        if (config('app.env') == 'prod') {
//            return 0;
//        }
//
//        return Redis::sismember(self::WHITE_PATH_SET, $path);
//    }
}
